package com.mall.common.controller;

import static com.mall.common.Constants.CACHE_NAME;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.b2c.util.JsonDataGridHelper;
import com.mall.common.bean.Pager;
import com.mall.common.util.CacheUtils;
import com.mall.common.util.ResponseUtils;
import com.mall.common.validation.annotation.RequiredStringValidator;
import com.mall.common.validation.annotation.Validations;

@Controller
@RequestMapping("/admin/system/dictionary")
public class DictionaryController extends BaseController{

	@Resource private JdbcTemplate jdbcTemplate;

	@RequestMapping(value="/manager", method=RequestMethod.GET)
	public String manager(){
		return "/admin/system/dictionary/manager";
	}

	@RequestMapping(value="/tree", method=RequestMethod.GET)
	public String tree(){
		return "/admin/system/dictionary/tree";
	}

	@RequestMapping(value="/treeData", method=RequestMethod.POST)
	@ResponseBody
	public List<Map<String, Object>> treeData(){
		List<Map<String, Object>> list = jdbcTemplate.queryForList(
				"select decode as id,name,description,LEFT(decode,LENGTH(decode)-3) parentId from s_dictionary order by decode");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", "");
		map.put("name", "全部");
		list.add(map);
		return list;
	}

	/**
	 * 跳转到字典页面
	 * @return
	 */
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String list(String parentCode, Model model){
		model.addAttribute("parentCode", parentCode);
		return "/admin/system/dictionary/list";
	}
	
	/**
	 * 查询字典数据
	 * @return
	 */
	@RequestMapping(value="/queryData", method=RequestMethod.POST)
	@ResponseBody
	public Pager queryData(String parentCode, Pager pager, HttpServletRequest request){
		String sql = "select decode,name,description from s_dictionary";
		if(StringUtils.isNotBlank(parentCode)){
			sql += " where decode like '" + parentCode + "%'";
		}
		sql += " order by decode";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		pager.setList(list);
		return JsonDataGridHelper.createJSONData(pager);
	}
	
	/**
	 * 数据字典树
	 * @return
	 */
	@RequestMapping(value="/getDictionaryByJson",method=RequestMethod.POST)
	public String getDictionaryByJson(HttpServletResponse response){
		List<Map<String, Object>> dictionaries = jdbcTemplate.queryForList("select decode,name,description from s_dictionary order by decode");
		JSONArray arr = new JSONArray();
		if(dictionaries != null && dictionaries.size() > 0){
			for(Map<String, Object> map : dictionaries){
				String decode = map.get("decode").toString();
				JSONObject jObject = new JSONObject();
				jObject.put("id", decode);
				jObject.put("pid", decode.substring(0, decode.length() - 3));
				jObject.put("text", map.get("name"));
				arr.add(jObject);
			}
		}
		return ResponseUtils.renderJSON(arr, response);
	}
	
	/**
	 * 新增数据字典
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String input(String parentCode, Model model){
		model.addAttribute("parentCode", parentCode);
		return "admin/system/dictionary/input";
	}
	
	/**
	 * 修改数据字典
	 * @return
	 */
	@RequestMapping(value="/edit/{decode}",method=RequestMethod.GET)
	public String editDictionary(@PathVariable String decode,Model model){
		List<Map<String, Object>> list = jdbcTemplate.queryForList(
		"select decode,name,description,config from s_dictionary where decode = "+decode);
		
		if(list.size()!=0){
			Map<String, Object> map=list.get(0);	
			if(map.get("decode") != null){
				decode = map.get("decode").toString();
				String parentCode = decode.substring(0, decode.length() - 3);
				model.addAttribute("parentCode", parentCode);
			}
			if(map.get("config") != null){
				String config = map.get("config").toString();
				JSONObject jsonObject = JSONObject.fromObject(config);
				model.addAttribute("configDetail", jsonObject);
			}
			model.addAllAttributes(map);
		}
		return "admin/system/dictionary/input";
	}

	/**
	 * 验证字典编码是否重复
	 * @param request 
	 * @return
	 */
    @RequestMapping(value="/checkName",method=RequestMethod.POST)
	public String checkName(HttpServletResponse response, HttpServletRequest request){
		String oldValue = request.getParameter("oldValue");
		String decode = request.getParameter("decode");
		if (oldValue != null && StringUtils.equalsIgnoreCase(oldValue, decode)) {
			return ResponseUtils.renderText("true", response);
		}
		if(jdbcTemplate.queryForList("select 1 from s_dictionary where decode = ?", new Object[]{decode}, String.class).size() == 0){
			return ResponseUtils.renderText("true", response);
		}
		return ResponseUtils.renderText("false", response);
	}
    
    /**
     * 生成编码
     * @param decode 当前编码
     * @param parentCode 父编码
     * @return
     */
    private String generateDecode(String decode, String parentCode){
    	String currentParent = null;
    	if(StringUtils.isNotBlank(decode)){
    		currentParent = decode.substring(0, decode.length() - 3);
    		jdbcTemplate.update("delete from s_dictionary where decode = ?", new Object[]{decode});
    		if(currentParent.equals(parentCode)){
    			return decode;
    		}
    	}else{
    		currentParent = parentCode;
    	}
    	if(StringUtils.isBlank(currentParent)
    			|| !currentParent.equals(parentCode) 
    			|| StringUtils.isBlank(decode)){
    		Object obj = null;
    		Long num = null;
    		if(StringUtils.isEmpty(parentCode)){
    			String decodeSql = "select max(decode) from s_dictionary where LENGTH(decode) = 3";
    			obj = jdbcTemplate.queryForObject(decodeSql, String.class);
    			if(obj != null){
    				num = Long.valueOf(obj.toString()) + 1;
    			}else{
    				num = 100L;
    			}
    		}else{
    			String decodeSql = "select max(decode) from s_dictionary where INSTR(decode,?) = 1 and LENGTH(decode) = LENGTH(?)+3";
        		obj = jdbcTemplate.queryForObject(decodeSql, new Object[]{parentCode, parentCode}, String.class);
        		if(obj != null){
        			num = Long.valueOf(obj.toString()) + 1;
        		}else{
        			num = Long.valueOf(parentCode) * 1000 + 1;
        		}
    		}
    		decode = num.toString();
    	}
    	return decode;
    }
	
	 /**
     * 保存
     * @return
     */
    @Validations(
		requiredStrings = {
				@RequiredStringValidator(fieldName = "name", message = "字典名称不允许为空!")
		}
	)
    @RequestMapping(value="/save",method=RequestMethod.POST)
	public String save(String parentCode, String name, 
			String description, String config, HttpServletResponse response){
    	Object[] objs = null;
    	int[] types = new int[]{Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR};
    	String decode = generateDecode(null, parentCode);
		objs = new Object[]{decode,name,description,config};
		String sql = "insert into s_dictionary(decode,name,description,config) values(?,?,?,?)";
		jdbcTemplate.update(sql, objs, types);
		parentCode = decode.substring(0, decode.length() - 3);
		CacheUtils.clearCache(CACHE_NAME);
    	Map<String, Object> dict = new HashMap<String, Object>();
    	dict.put("id", decode);
    	dict.put("name", name);
    	dict.put("parentId", parentCode);
    	return ResponseUtils.renderJSON(dict, response);//("保存成功");
	}
    
	 /**
     * 修改
     * @return
     */
    @Validations(
		requiredStrings = {
				@RequiredStringValidator(fieldName = "decode", message = "字典编码不允许为空!"),
				@RequiredStringValidator(fieldName = "name", message = "字典名称不允许为空!")
		}
	)
    @RequestMapping(value="/update",method=RequestMethod.POST)
	public String save(String decode, String parentCode, String name, 
			String description, String config, HttpServletResponse response){
    	Object[] objs = null;
    	int[] types = new int[]{Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR};
    	decode = generateDecode(decode, parentCode);
		objs = new Object[]{decode,name,description,config};
		String sql = "insert into s_dictionary(decode,name,description,config) values(?,?,?,?)";
		jdbcTemplate.update(sql, objs, types);
		parentCode = decode.substring(0, decode.length() - 3);
    	CacheUtils.clearCache(CACHE_NAME);
    	Map<String, Object> dict = new HashMap<String, Object>();
    	dict.put("id", decode);
    	dict.put("name", name);
    	dict.put("parentId", parentCode);
    	return ResponseUtils.renderJSON(dict, response);//("保存成功");
	}
    
    /**
     * 删除数据字典
     * @return
     */
    @RequestMapping(value="/delete",method=RequestMethod.POST)
    @ResponseBody
    public String delete(String[] decodes, HttpServletResponse response){
    	for(String decode : decodes){
        	jdbcTemplate.update("delete from s_dictionary where decode = ?", new Object[]{decode});
    	}
    	CacheUtils.clearCache(CACHE_NAME);
		return ResponseUtils.renderJSON(successMessage,response);
    }
    
    /**
     * 重新初始化
     * @return
     */
    @RequestMapping(value="/reinit",method=RequestMethod.POST)
    public String reinit(HttpServletResponse response){
    	CacheUtils.clearCache(CACHE_NAME);
		return ResponseUtils.renderJSON(successMessage, response);//"初始化成功";
    }

}
